import sys
import re
import tkinter as tk
from tkinter import filedialog, messagebox

# ---------------------------------------------------
# 原功能：字符、单词、句子统计
# ---------------------------------------------------

def count_characters(text):
    return len(text)

def count_words(text):
    words = re.findall(r"[A-Za-z]+", text)
    return len(words)

def count_sentences(text):
    sentences = re.findall(r"[\.!?]", text)
    return len(sentences)

# ---------------------------------------------------
# 新功能：统计代码行、空行、注释行
# ---------------------------------------------------

def count_lines_info(text):
    lines = text.splitlines()

    total = len(lines)
    empty = 0
    comment = 0
    code = 0

    inside_block = False

    for line in lines:
        stripped = line.strip()

        # 空行统计
        if stripped == "":
            empty += 1
            continue

        # 块注释开始
        if stripped.startswith("/*"):
            comment += 1
            inside_block = True
            continue

        # 块注释中
        if inside_block:
            comment += 1
            if "*/" in stripped:
                inside_block = False
            continue

        # 单行注释
        if stripped.startswith("#") or stripped.startswith("//"):
            comment += 1
            continue

        # 剩下的视为代码行
        code += 1

    return total, empty, comment, code

# ---------------------------------------------------
# GUI 可视化界面
# ---------------------------------------------------

class WC_GUI:
    def __init__(self, root):
        self.root = root
        self.root.title("文本统计工具  —  WC Viewer")
        self.root.geometry("600x400")

        self.filename = None
        self.text = ""

        # 顶部信息输出框
        self.output_label = tk.Label(root, text="请选择文件进行统计", font=("Arial", 14))
        self.output_label.pack(pady=15)

        # 文件选择按钮
        select_btn = tk.Button(root, text="选择文件", font=("Arial", 12),
                               command=self.select_file, width=20)
        select_btn.pack(pady=5)

        # 按钮区域
        btn_frame = tk.Frame(root)
        btn_frame.pack(pady=20)

        # 添加所有功能按钮
        tk.Button(btn_frame, text="统计字符数", width=15,
                  command=self.show_char_count).grid(row=0, column=0, padx=10, pady=10)

        tk.Button(btn_frame, text="统计单词数", width=15,
                  command=self.show_word_count).grid(row=0, column=1, padx=10, pady=10)

        tk.Button(btn_frame, text="统计句子数", width=15,
                  command=self.show_sentence_count).grid(row=1, column=0, padx=10, pady=10)

        tk.Button(btn_frame, text="统计总行数", width=15,
                  command=self.show_total_lines).grid(row=1, column=1, padx=10, pady=10)

        tk.Button(btn_frame, text="统计代码行", width=15,
                  command=self.show_code_lines).grid(row=2, column=0, padx=10, pady=10)

        tk.Button(btn_frame, text="统计空行", width=15,
                  command=self.show_empty_lines).grid(row=2, column=1, padx=10, pady=10)

        tk.Button(btn_frame, text="统计注释行", width=15,
                  command=self.show_comment_lines).grid(row=3, column=0, padx=10, pady=10)

        tk.Button(btn_frame, text="全部统计", width=15,
                  command=self.show_all).grid(row=3, column=1, padx=10, pady=10)

    # ---------------------------------------------------
    # 文件选择
    # ---------------------------------------------------
    def select_file(self):
        path = filedialog.askopenfilename(
            title="选择文本文件",
            filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
        )
        if not path:
            return

        self.filename = path
        try:
            with open(path, "r", encoding="utf-8") as f:
                self.text = f.read()
            self.output_label.config(text=f"已打开文件：{path}")
        except Exception as e:
            messagebox.showerror("错误", f"无法打开文件：{e}")

    # ---------------------------------------------------
    # GUI 输出辅助函数
    # ---------------------------------------------------
    def update_output(self, msg):
        self.output_label.config(text=msg)

    # ---------------------------------------------------
    # 按钮对应功能
    # ---------------------------------------------------
    def show_char_count(self):
        if not self.text:
            return
        count = count_characters(self.text)
        self.update_output(f"文件 {self.filename} 的字符数为：{count}")

    def show_word_count(self):
        if not self.text:
            return
        count = count_words(self.text)
        self.update_output(f"文件 {self.filename} 的单词数为：{count}")

    def show_sentence_count(self):
        if not self.text:
            return
        count = count_sentences(self.text)
        self.update_output(f"文件 {self.filename} 的句子数为：{count}")

    def show_total_lines(self):
        if not self.text:
            return
        total, _, _, _ = count_lines_info(self.text)
        self.update_output(f"文件 {self.filename} 的总行数为：{total}")

    def show_code_lines(self):
        if not self.text:
            return
        _, _, _, code = count_lines_info(self.text)
        self.update_output(f"文件 {self.filename} 的代码行数为：{code}")

    def show_empty_lines(self):
        if not self.text:
            return
        _, empty, _, _ = count_lines_info(self.text)
        self.update_output(f"文件 {self.filename} 的空行数为：{empty}")

    def show_comment_lines(self):
        if not self.text:
            return
        _, _, comment, _ = count_lines_info(self.text)
        self.update_output(f"文件 {self.filename} 的注释行数为：{comment}")

    def show_all(self):
        if not self.text:
            return
        total, empty, comment, code = count_lines_info(self.text)
        msg = (f"文件 {self.filename} 的统计结果：\n"
               f"总行数：{total}    空行：{empty}\n"
               f"注释行：{comment}   代码行：{code}")
        self.update_output(msg)

# ---------------------------------------------------
# 主程序入口
# ---------------------------------------------------

if __name__ == "__main__":
    root = tk.Tk()
    app = WC_GUI(root)
    root.mainloop()
